<template>
  <div class="organization-manage-page">
    <div class="left">
      <el-card class="card">
        <el-tree
          class="tree"
          :data="treeList"
          :props="treeDefaultProps"
          node-key="id"
          :expand-on-click-node="false"
          :current-node-key="currentNodeKey"
          :default-expanded-keys="[currentNodeKey]"
          highlight-current
          @current-change="handleSelectTreeNode"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <!-- 没有子节点，也就是叶子节点 -->
            <svg-icon v-if="!data.children" style="margin-right: 0px;" icon-class="" class="tree-icon svgIcon" />
            <!-- 展开 -->
            <svg-icon v-else-if="node.expanded" icon-class="floder-open" class=" tree-icon svgIcon" />
            <!-- 关闭 -->
            <svg-icon v-else icon-class="floder-close" class="tree-icon svgIcon" />
            <!-- 节点文字 -->
            <span class="tree-icon-text" :title="node.label">{{ node.label }}</span>
          </span>
        </el-tree>
      </el-card>
    </div>

    <div class="right">
      <el-card class="card">
        <div slot="header" class="clearfix">
          <span>机构信息</span>
        </div>

        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row type="flex" justify="space-between" align="middle">
            <el-form-item label="机构编号" prop="id">
              <el-input v-model="form.id" disabled />
            </el-form-item>

            <el-form-item label="机构名称" prop="name">
              <el-input v-model="form.name" disabled />
            </el-form-item>

            <el-form-item label="机构类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" disabled>
                <el-option
                  v-for="item in organizationTypeOptionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>

          <el-row type="flex" justify="space-between" align="middle">
            <el-form-item label="机构地址" style="width: 100%">
              <el-row justify="space-between" align="middle">
                <el-col :span="8">
                  <!-- 省份 -->
                  <el-select
                    ref="provinceSelect"
                    v-model="form.provinceId"
                    placeholder="请选择省"
                    :disabled="!isEditMode"
                    clearable
                    @change="onProvinceSelctChange"
                    @clear="onProvinceSelectClear"
                  >
                    <el-option
                      v-for="item in provinceOptionList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>

                <el-col :span="8" style="padding: 0 2px">
                  <!-- 城市 -->
                  <el-select
                    v-model="form.cityId"
                    placeholder="请选择市"
                    clearable
                    :disabled="!isEditMode"
                    @change="onCitySelctChange"
                    @clear="onCitySelectClear"
                  >
                    <el-option
                      v-for="item in cityOptionList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>

                <el-col :span="8">
                  <!-- 区 -->
                  <el-select
                    v-model="form.countyId"
                    placeholder="请选择县/区"
                    clearable
                    :disabled="!isEditMode"
                    @change="onCountySelctChange"
                  >
                    <el-option
                      v-for="item in countyOptionList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-row>

          <el-row type="flex" justify="space-between" align="middle">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" :disabled="!isEditMode" />
            </el-form-item>

            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" disabled>
                <template slot="append">E</template>
              </el-input>
            </el-form-item>

            <el-form-item label="纬度" prop="longitude">
              <el-input v-model="form.latitude" disabled>
                <template slot="append">N</template>
              </el-input>
            </el-form-item>
          </el-row>

          <el-row type="flex" justify="start" align="middle">
            <el-form-item label="机构负责人" prop="managerName">
              <el-input
                v-model="form.managerName"
                :disabled="!isEditMode"
              />
            </el-form-item>

            <el-form-item label="机构电话" prop="phone">
              <el-input v-model="form.phone" :disabled="!isEditMode" />
            </el-form-item>
          </el-row>

          <el-row type="flex" justify="center" align="middle">
            <el-button type="primary" @click="switchMode">{{
              isEditMode ? "保存" : "编辑"
            }}</el-button>
          </el-row>
        </el-form>
      </el-card>

      <el-card class="card" style="margin-top: 20px">
        <div slot="header" class="clearfix">
          <span>员工信息</span>
        </div>
        <!-- 员工表格 -->
        <el-table class="table" :data="list" style="width: 100%">
          <el-table-column
            prop="date"
            type="index"
            label="序号"
            :index="indexMethod"
          />
          <el-table-column prop="userId" label="员工编号" />
          <el-table-column prop="name" label="员工姓名" />
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="date" label="所属机构">
            <template #default="{ row }">
              <span>{{ row.agency ? row.agency.name : "" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="account" label="系统账户" />
          <el-table-column prop="date" label="系统角色">
            <template #default="{ row }">
              <span>{{ roleNameText(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="账号状态">
            <template #default="{ row }">
              <span>{{ row.status === 0 ? "禁用" : "正常" }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :current-page.sync="queryParams.page"
            :page-size="queryParams.pageSize"
            :total="counts"
            layout="total, prev, pager, next"
            @current-change="handlePageChange"
          />
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getOrganizationTreeList,
  getEmployeePageList,
  getOrganizationDetail,
  updateOrganization
} from '@/api/organization'
import { getProvinceList, getAreasList } from '@/api/area'
import { getTreeNodeFirstLeafNode } from '@/utils/index'
import {
  getOrganizationTypeList,
  getOrganizationTypeLabelByCode
} from '@/utils/organization-data'
import { calItemNum } from '@/utils/page'

export default {
  name: 'OrganizationManagePage',
  data() {
    return {
      // 是否是编辑模式
      isEditMode: false,
      // 机构树形数据
      treeList: [],
      // 员工列表
      list: [],
      // 树形结构的字段映射配置
      treeDefaultProps: {
        label: 'name',
        children: 'children'
      },
      // 查询参数
      queryParams: {
        // 司机编号
        account: '',
        // 机构Id
        agencyId: '',
        // 司机名称
        name: '',
        page: 1,
        pageSize: 3,
        // 手机号
        phone: ''
      },
      // 机构下拉选择列表
      organizationTypeOptionList: getOrganizationTypeList(),
      // 地区-省份，下拉选择列表
      provinceOptionList: [],
      // 地区-城市，下拉选择列表
      cityOptionList: [],
      // 地区-区，下拉选择列表
      countyOptionList: [],
      // 机构详情-表单数据
      form: {
        // 省份Id
        provinceId: '',
        // 城市Id
        cityId: '',
        // 区Id
        countyId: ''
      },
      // 机构详情-表单校验规则
      rules: {
        // 详细地址
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        // 机构负责人
        managerName: [
          { required: true, message: '请输入机构负责人', trigger: 'blur' }
        ],
        // 机构电话
        phone: [{ required: true, message: '请输入机构电话', trigger: 'blur' }]
      },
      // 当前选择的节点的Id
      currentNodeKey: '1024985257948084801',
      // 总条数
      counts: 0
    }
  },
  computed: {
    // 角色
    roleNameText() {
      return (row) => {
        if (!row.roleNames) {
          return ''
        }
        return row.roleNames.join(', ')
      }
    }
  },
  created() {
    this.getOrganizationTreeList()
  },
  methods: {
    // 计算序号
    indexMethod(index) {
      return calItemNum(
        index,
        this.queryParams.page,
        this.queryParams.pageSize
      )
    },
    // 切换编辑状态
    async switchMode() {
      // 编辑状态，则更新机构信息
      if (this.isEditMode) {
        try {
          // 表单校验
          await this.$refs.form.validate()
          // 手动校验省市区的选择
          if (!this.form.provinceId) {
            this.$message.error('请选择省')
            return
          }
          if (!this.form.cityId) {
            this.$message.error('请选择市')
            return
          }
          if (!this.form.countyId) {
            this.$message.error('请选择县/区')
            return
          }
          console.log('表单校验 => 通过')
          // 发出请求
          const result = await updateOrganization(this.form)
          console.log(result)
          // 更新成功，切回普通状态
          this.isEditMode = !this.isEditMode
        } catch (e) {
          console.log('更新机构信息 => 失败', e)
        }
      } else {
        // 非编辑状态，则切回普通状态
        this.isEditMode = !this.isEditMode
      }
    },
    // 获取省份列表
    async getProvinceOptionList() {
      const result = await getProvinceList()
      console.log(result)
      this.provinceOptionList = result.data
    },
    // 获取城市列表
    async getCityOptionList(provinceId) {
      const result = await getAreasList(provinceId)
      console.log(result)
      this.cityOptionList = result.data
    },
    // 获取区列表
    async getCountyOptionList(cityId) {
      const result = await getAreasList(cityId)
      console.log(result)
      this.countyOptionList = result.data
    },
    // 获取结构树形列表
    async getOrganizationTreeList() {
      const result = await getOrganizationTreeList()
      console.log(result)

      // 解析返回的树形数据为数组
      const dataJson = result.data
      // 更新机构树形数据
      this.treeList = JSON.parse(dataJson)

      const firstLeafNode = getTreeNodeFirstLeafNode(this.treeList[0])
      console.log('第一个叶子节点：', firstLeafNode)

      // 获取第一个机构，并默认选中它
      this.queryParams.agencyId = firstLeafNode.id
      // 设置树形组件，当前选中的id
      this.currentNodeKey = this.queryParams.agencyId
      console.log(`进入页面，默认选中的机构Id => ${this.currentNodeKey}`)

      // 获取该机构的详情数据
      this.getOrganizationDetail()
      // 获取该机构下的所有员工
      this.getEmployeePageList()
    },
    // 获取机构详情
    async getOrganizationDetail() {
      // 获取详情数据
      const result = await getOrganizationDetail(this.queryParams.agencyId)
      console.log(result)

      const provinceId = result.data.province.id
      console.log(`省份Id => ${provinceId}`)
      const cityId = result.data.city.id
      console.log(`城市Id => ${cityId}`)
      const countyId = result.data.county.id
      console.log(`区Id => ${countyId}`)

      // 获取机构的地区信息
      await this.getProvinceOptionList()
      await this.getCityOptionList(provinceId)
      await this.getCountyOptionList(cityId)

      // 回填表单数据
      this.form = result.data

      // 处理机构类型
      this.form.type = getOrganizationTypeLabelByCode(result.data.type)

      // 处理省份
      this.form.provinceId = provinceId

      // 处理城市
      this.form.cityId = cityId

      // 处理区
      this.form.countyId = countyId
    },
    // 获取员工列表
    async getEmployeePageList() {
      const result = await getEmployeePageList(this.queryParams)
      console.log(result)
      // 更新员工列表
      this.list = result.data.items
      // 更新总条数
      this.counts = +result.data.counts
    },
    // 处理选中的树形节点改变
    handleSelectTreeNode(node) {
      console.log(node)
      // 更新当前选中的节点id
      this.queryParams.agencyId = node.id
      // 重置页码为第一页
      this.queryParams.page = 1
      // 查询机构详情
      this.getOrganizationDetail()
      // 查询机构员工列表
      this.getEmployeePageList()
    },
    // 处理分页切换
    handlePageChange(page) {
      this.queryParams.page = page
      this.getEmployeePageList()
    },
    onProvinceSelctChange(provinceId) {
      console.log(`选择了省份 => ${provinceId}`)
      // 获取市选择列表
      this.getCityOptionList(provinceId)
      // 清空市和区
      this.$set(this.form, 'cityId', '')
      this.$set(this.form, 'countyId', '')
      this.$forceUpdate()
    },
    onCitySelctChange(cityId) {
      console.log(`选择了市 => ${cityId}`)
      // 获取区选择列表
      this.getCountyOptionList(cityId)
      // 清空区
      this.$set(this.form, 'countyId', '')
      this.$forceUpdate()
    },
    onCountySelctChange(countyId) {
      console.log(`选择了区 => ${countyId}`)
      this.form.countyId = countyId
      this.$forceUpdate()
    },
    onProvinceSelectClear() {
      console.log('清空 => 省份选择')
      // 清空市和区
      this.$set(this.form, 'cityId', '')
      this.$set(this.form, 'countyId', '')
      this.$forceUpdate()
    },
    onCitySelectClear() {
      console.log('清空 => 城市选择')
      // 清空区
      this.$set(this.form, 'countyId', '')
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
// 自定义图标中隐藏自带箭头
::v-deep .el-tree-node__content>.el-tree-node__expand-icon {
  position: absolute;
  opacity: 0;
}

// 树节点图标
.tree-icon {
  width: 14px;
  height: 14px;
  margin-right: 8px;
}

// 树节点文字
.tree-icon-text {
  font-size: 14px;
  font-weight: 400;
  color: #818693;
}

.organization-manage-page {
  display: flex;
  flex-direction: row;
  padding: 20px;
  background-color: #f3f5f9;

  .el-select {
    width: 100%;
  }

  .left {
    width: 205px;
    height: 823px;
    margin-right: 20px;

    .card {
      height: 100%;
    }

    .tree {
      height: 100%;
    }
  }

  .right {
    flex: 1;
    height: 100%;

    .table {
      height: 260px;
    }
  }
}
</style>
